package com.baozheyangken.ai_learn.service.serviceImpl;

import com.baozheyangken.ai_learn.context.BaseContext;
import com.baozheyangken.ai_learn.exception.AccountLockedException;
import com.baozheyangken.ai_learn.exception.AccountNotFoundException;
import com.baozheyangken.ai_learn.exception.PasswordErrorException;
import com.baozheyangken.ai_learn.mapper.UserMapper;
import com.baozheyangken.ai_learn.pojo.dto.UserDTO;
import com.baozheyangken.ai_learn.pojo.entity.Permission;
import com.baozheyangken.ai_learn.pojo.entity.User;
import com.baozheyangken.ai_learn.pojo.result.Result;
import com.baozheyangken.ai_learn.pojo.vo.UserLoginVO;
import com.baozheyangken.ai_learn.pojo.vo.UserVO;
import com.baozheyangken.ai_learn.service.UserService;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 注册
     *
     * @param userVO
     * @return
     */
    @Override
    @Transactional
    public Result<UserDTO> userRegister(UserVO userVO) {
        // 先判断用户是否已存在
        Integer userId = userMapper.getIdByUsername(userVO.getUsername());
        Integer email = userMapper.getIdByEmail(userVO.getEmail());
        if (userId != null)
            return Result.error("用户名已存在");
        if (email != null)
            return Result.error("该邮箱已被注册");

        User user = new User();
        BeanUtils.copyProperties(userVO, user);

        // md5
        user.setPassword(DigestUtils.md5DigestAsHex(userVO.getPassword().getBytes()));

        // 用户表新增用户
        userMapper.register(user);
        userId = user.getId();
        log.info("userId:{}", userId);

        // 新增角色关联表,默认2
        userMapper.setRoleId(userId, 2);

        UserDTO userDTO = UserDTO.builder()
                .id(userId)
                .username(user.getUsername())
                .email(user.getEmail())
                .build();
        return Result.success(userDTO);
    }

    /**
     * 登入
     *
     * @param userLoginVO
     * @return
     */
    @Override
    public User userLogin(UserLoginVO userLoginVO) {
        String username = userLoginVO.getUsername();
        String password = userLoginVO.getPassword();
        User user = userMapper.login(username);
        log.info("user:{}", user);
        // md5
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        if (user == null)
            throw new AccountNotFoundException("账号不存在");

        if (!password.equals(user.getPassword()))
            throw new PasswordErrorException("密码错误");

        if (user.getStatus() == 0)
            throw new AccountLockedException("账号被锁定");

        return user;
    }

    /**
     * 获取用户信息
     *
     * @return User
     */
    @Override
    public User userInfo() {
        Integer id = BaseContext.getCurrentId();
        User user = userMapper.getUserById(id);
        if (user != null) {
            user.setPassword("******");
        }
        log.info("user:{}", user);
        return user;
    }

    @Override
    public Result<UserDTO> userUpdate(Integer id,String username, String email, String password, String oldPassword) {
        userMapper.updateUser(id,username,email,password);
        return Result.success();
    }

    /**
     * 修改当前用户信息
     *
     * @param email
     * @param password
     * @param oldPassword
     * @return
     */
    //@Override
    @Transactional
    public Result<UserDTO> userUpdate(String email, String password, String oldPassword) {
        log.info("email:{},password:{},oldPassword:{}", email, password, oldPassword);
        if (email == null && (oldPassword == null && password == null))
            return Result.error("未输入要修改的内容");

        Integer id = BaseContext.getCurrentId();
        if (email != null) {
            // 查看新邮箱是否已被占用
            Integer userId = userMapper.getIdByEmail(email);
            if (userId != null) {
                return Result.error("邮箱已被占用");
            } else {
                // 更新email
                userMapper.updateUser(id, email, password);
            }
        }

        if (password != null) {
            if (oldPassword == null) {
                return Result.error("原来密码为空");
            } else {
                // 查看原密码是否正确
                User user = userMapper.getUserById(id);
                String md5Password = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
                if (user.getPassword().equals(md5Password)) {
                    // 更新密码
                    password = DigestUtils.md5DigestAsHex(password.getBytes());
                    userMapper.updateUser(id, email, password);
                } else
                    return Result.error("原密码不正确");
            }
        }

        User user = userMapper.getUserById(id);
        UserDTO userDTO = UserDTO.builder()
                .id(id)
                .username(user.getUsername())
                .email(user.getEmail())
                .build();

        return Result.success(userDTO);
    }

    /**
     * 软删除用户
     *
     * @param id
     */
    @Override
    public Result userDelete(Integer id) {
        Integer currentUserId = BaseContext.getCurrentId();
        List<Integer> roleIds = userMapper.getRoleIdByUserId(currentUserId);
        // 判断当前用户是不是管理员
        if (!roleIds.contains(1)) {
            return Result.error("没有权限删除");
        }
        userMapper.setUserStatus(id);
        return Result.success();
    }

    /**
     * 获取用户当前权限
     *
     * @return
     */
    @Override
    public List<String> userPermission() {
        Integer id = BaseContext.getCurrentId();
        List<Integer> roleIds = userMapper.getRoleIdByUserId(id);
        List<Permission> permissions = userMapper.getUserPermission(roleIds);
        //log.info("permissions:{}", permissions);

        List<String> permissionList = new ArrayList<>();
        permissions.forEach(permission -> {
            permissionList.add(permission.getDescription()); // 假设使用permissionName作为权限标识
        });

        return permissionList;
    }

    @Override
    public List<User> getAllUsers() {
        // 实现获取所有用户的逻辑
        return userMapper.getAllUsers();
    }

    @Override
    @Transactional
    public User addUser(User user) {
        // 实现添加新用户的逻辑
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        userMapper.register(user);
        Integer userId = user.getId();
        userMapper.setRoleId(userId, 2); // 默认角色为教师
        return user;
    }

    @Override
    @Transactional
    public User updateUser(User user) {
        // 实现更新用户信息的逻辑
        //todo 更新后的密码应该用md5加密在存到 sql
        userMapper.updateUser(user.getId(), user.getEmail(), user.getPassword());
        return user;
    }

    @Override
    public void deleteUser(Integer id) {
        // 实现删除用户的逻辑
        userMapper.setUserStatus(id);
    }

    @Override
    public void resetPassword(Integer id) {
        // 实现重置用户密码的逻辑
        String defaultPassword = "123456"; // 默认密码
        String md5Password = DigestUtils.md5DigestAsHex(defaultPassword.getBytes());
        userMapper.updateUser(id, null, md5Password);
    }
}